"""
期刊格式适配器

提供多期刊格式支持、格式自动转换算法和格式验证机制功能
"""

import logging
import json
import re
from typing import Dict, List, Optional, Any, Tuple, Union, Callable
from dataclasses import dataclass, field
from enum import Enum
import datetime
from pathlib import Path

from ..models.base_models import BaseModel
from .base_component import BaseComponent

logger = logging.getLogger(__name__)


class JournalType(Enum):
    """期刊类型"""
    IEEE = "ieee"                              # IEEE期刊
    ACM = "acm"                               # ACM期刊
    SPRINGER = "springer"                      # Springer期刊
    ELSEVIER = "elsevier"                     # Elsevier期刊
    NATURE = "nature"                         # Nature期刊
    SCIENCE = "science"                       # Science期刊
    PLOS = "plos"                            # PLOS期刊
    MDPI = "mdpi"                            # MDPI期刊
    WILEY = "wiley"                          # Wiley期刊
    TAYLOR_FRANCIS = "taylor_francis"         # Taylor & Francis期刊
    SAGE = "sage"                            # SAGE期刊
    OXFORD = "oxford"                        # Oxford期刊
    CAMBRIDGE = "cambridge"                   # Cambridge期刊
    GENERIC = "generic"                       # 通用格式


class CitationStyle(Enum):
    """引用格式"""
    APA = "apa"                              # APA格式
    MLA = "mla"                              # MLA格式
    CHICAGO = "chicago"                       # Chicago格式
    HARVARD = "harvard"                       # Harvard格式
    IEEE_STYLE = "ieee_style"                 # IEEE引用格式
    VANCOUVER = "vancouver"                   # Vancouver格式
    NATURE_STYLE = "nature_style"             # Nature引用格式
    SCIENCE_STYLE = "science_style"           # Science引用格式


class FormatElement(Enum):
    """格式元素"""
    TITLE = "title"                          # 标题
    AUTHOR = "author"                        # 作者
    AFFILIATION = "affiliation"              # 机构
    ABSTRACT = "abstract"                    # 摘要
    KEYWORDS = "keywords"                    # 关键词
    INTRODUCTION = "introduction"            # 引言
    METHODOLOGY = "methodology"              # 方法
    RESULTS = "results"                      # 结果
    DISCUSSION = "discussion"                # 讨论
    CONCLUSION = "conclusion"                # 结论
    REFERENCES = "references"                # 参考文献
    FIGURES = "figures"                      # 图片
    TABLES = "tables"                        # 表格
    APPENDIX = "appendix"                    # 附录
    ACKNOWLEDGMENTS = "acknowledgments"       # 致谢


@dataclass
class FormatRule(BaseModel):
    """格式规则"""
    element: FormatElement = FormatElement.TITLE
    rule_type: str = "formatting"  # formatting, structure, content
    description: str = ""
    
    # 格式要求
    font_family: Optional[str] = None
    font_size: Optional[int] = None
    font_weight: Optional[str] = None  # normal, bold
    font_style: Optional[str] = None   # normal, italic
    
    # 间距要求
    line_spacing: Optional[float] = None
    paragraph_spacing: Optional[float] = None
    margin_top: Optional[float] = None
    margin_bottom: Optional[float] = None
    
    # 对齐方式
    alignment: Optional[str] = None  # left, center, right, justify
    
    # 内容要求
    max_length: Optional[int] = None
    min_length: Optional[int] = None
    required_elements: List[str] = field(default_factory=list)
    forbidden_elements: List[str] = field(default_factory=list)
    
    # 格式模式
    format_pattern: Optional[str] = None
    validation_regex: Optional[str] = None
    
    # 特殊要求
    numbering_style: Optional[str] = None
    capitalization: Optional[str] = None  # title, sentence, upper, lower
    
    def validate_content(self, content: str) -> Tuple[bool, List[str]]:
        """验证内容是否符合规则"""
        errors = []
        
        # 长度检查
        if self.max_length and len(content) > self.max_length:
            errors.append(f"内容长度超过限制 ({len(content)} > {self.max_length})")
        
        if self.min_length and len(content) < self.min_length:
            errors.append(f"内容长度不足 ({len(content)} < {self.min_length})")
        
        # 正则验证
        if self.validation_regex and not re.match(self.validation_regex, content):
            errors.append(f"内容格式不符合要求")
        
        # 必需元素检查
        for required in self.required_elements:
            if required.lower() not in content.lower():
                errors.append(f"缺少必需元素: {required}")
        
        # 禁止元素检查
        for forbidden in self.forbidden_elements:
            if forbidden.lower() in content.lower():
                errors.append(f"包含禁止元素: {forbidden}")
        
        return len(errors) == 0, errors


@dataclass
class JournalFormat(BaseModel):
    """期刊格式"""
    format_id: str = ""
    journal_name: str = ""
    journal_type: JournalType = JournalType.GENERIC
    publisher: str = ""
    
    # 基本信息
    description: str = ""
    version: str = "1.0"
    last_updated: datetime.datetime = field(default_factory=datetime.datetime.now)
    
    # 页面设置
    page_size: str = "A4"  # A4, Letter, etc.
    page_margins: Dict[str, float] = field(default_factory=lambda: {
        'top': 2.5, 'bottom': 2.5, 'left': 2.5, 'right': 2.5
    })
    
    # 字体设置
    default_font_family: str = "Times New Roman"
    default_font_size: int = 12
    default_line_spacing: float = 1.5
    
    # 引用格式
    citation_style: CitationStyle = CitationStyle.APA
    reference_format: str = ""
    
    # 格式规则
    format_rules: Dict[str, FormatRule] = field(default_factory=dict)
    
    # 结构要求
    required_sections: List[str] = field(default_factory=list)
    optional_sections: List[str] = field(default_factory=list)
    section_order: List[str] = field(default_factory=list)
    
    # 限制要求
    word_limit: Optional[Tuple[int, int]] = None
    page_limit: Optional[Tuple[int, int]] = None
    reference_limit: Optional[int] = None
    figure_limit: Optional[int] = None
    table_limit: Optional[int] = None
    
    # 特殊要求
    special_requirements: List[str] = field(default_factory=list)
    submission_guidelines: Dict[str, Any] = field(default_factory=dict)
    
    def add_format_rule(self, element: FormatElement, rule: FormatRule):
        """添加格式规则"""
        self.format_rules[element.value] = rule
        self.last_updated = datetime.datetime.now()
    
    def get_format_rule(self, element: FormatElement) -> Optional[FormatRule]:
        """获取格式规则"""
        return self.format_rules.get(element.value)
    
    def validate_structure(self, sections: List[str]) -> Tuple[bool, List[str]]:
        """验证结构"""
        errors = []
        
        # 检查必需章节
        for required in self.required_sections:
            if required not in sections:
                errors.append(f"缺少必需章节: {required}")
        
        # 检查章节顺序
        if self.section_order:
            section_indices = {}
            for i, section in enumerate(sections):
                if section in self.section_order:
                    section_indices[section] = i
            
            for i in range(len(self.section_order) - 1):
                current_section = self.section_order[i]
                next_section = self.section_order[i + 1]
                
                if (current_section in section_indices and 
                    next_section in section_indices and
                    section_indices[current_section] > section_indices[next_section]):
                    errors.append(f"章节顺序错误: {current_section} 应在 {next_section} 之前")
        
        return len(errors) == 0, errors


@dataclass
class FormatConversionResult(BaseModel):
    """格式转换结果"""
    success: bool = True
    error_message: str = ""
    
    # 转换信息
    source_format: str = ""
    target_format: str = ""
    conversion_time: datetime.datetime = field(default_factory=datetime.datetime.now)
    
    # 转换内容
    converted_content: Dict[str, str] = field(default_factory=dict)
    
    # 转换统计
    elements_converted: int = 0
    warnings: List[str] = field(default_factory=list)
    
    # 验证结果
    validation_passed: bool = True
    validation_errors: List[str] = field(default_factory=list)
    
    # 质量评估
    conversion_quality: float = 0.0
    format_compliance: float = 0.0


@dataclass
class AdapterConfig(BaseModel):
    """适配器配置"""
    # 转换设置
    preserve_formatting: bool = True
    auto_fix_errors: bool = True
    strict_validation: bool = False
    
    # 内容处理
    normalize_whitespace: bool = True
    fix_encoding: bool = True
    remove_comments: bool = False
    
    # 引用处理
    convert_citations: bool = True
    validate_references: bool = True
    
    # 图表处理
    resize_figures: bool = True
    reformat_tables: bool = True
    
    # 质量控制
    min_quality_threshold: float = 0.8
    max_warnings: int = 10


class JournalFormatAdapter(BaseComponent):
    """期刊格式适配器"""
    
    def get_required_configs(self) -> List[str]:
        """获取必需的配置项"""
        return []
    
    def _setup_component(self):
        """设置组件特定的初始化逻辑"""
        self.logger.info("期刊格式适配器初始化")
        
        # 加载期刊格式定义
        self.journal_formats: Dict[str, JournalFormat] = {}
        self._initialize_journal_formats()
        
        # 格式转换器
        self.format_converters = {
            'citation': self._convert_citations,
            'reference': self._convert_references,
            'title': self._convert_title_format,
            'author': self._convert_author_format,
            'abstract': self._convert_abstract_format,
            'section': self._convert_section_format,
            'figure': self._convert_figure_format,
            'table': self._convert_table_format
        }
        
        # 验证器
        self.validators = {
            'structure': self._validate_structure,
            'content': self._validate_content,
            'formatting': self._validate_formatting,
            'references': self._validate_references
        }
        
        self.logger.info("期刊格式适配器初始化完成")    

    def convert_format(self, 
                      content: Dict[str, str],
                      source_format: str,
                      target_format: str,
                      config: AdapterConfig = None) -> FormatConversionResult:
        """
        转换格式
        
        Args:
            content: 原始内容
            source_format: 源格式ID
            target_format: 目标格式ID
            config: 适配器配置
            
        Returns:
            格式转换结果
        """
        try:
            if config is None:
                config = AdapterConfig()
            
            # 获取格式定义
            source_journal = self.journal_formats.get(source_format)
            target_journal = self.journal_formats.get(target_format)
            
            if not target_journal:
                raise ValueError(f"未找到目标格式: {target_format}")
            
            # 初始化结果
            result = FormatConversionResult(
                source_format=source_format,
                target_format=target_format
            )
            
            # 转换各个元素
            converted_content = {}
            elements_converted = 0
            
            for element_name, element_content in content.items():
                if element_content and element_content.strip():
                    try:
                        converted_element = self._convert_element(
                            element_name, element_content, source_journal, target_journal, config
                        )
                        converted_content[element_name] = converted_element
                        elements_converted += 1
                    except Exception as e:
                        result.warnings.append(f"转换 {element_name} 时出错: {str(e)}")
                        converted_content[element_name] = element_content  # 保持原内容
            
            result.converted_content = converted_content
            result.elements_converted = elements_converted
            
            # 验证转换结果
            validation_result = self.validate_format(converted_content, target_format)
            result.validation_passed = validation_result['is_valid']
            result.validation_errors = validation_result['errors']
            
            # 计算质量评分
            result.conversion_quality = self._calculate_conversion_quality(result)
            result.format_compliance = self._calculate_format_compliance(
                converted_content, target_journal
            )
            
            self.logger.info(f"格式转换完成: {source_format} -> {target_format}")
            return result
            
        except Exception as e:
            self.logger.error(f"格式转换失败: {str(e)}")
            return FormatConversionResult(
                success=False,
                error_message=str(e),
                source_format=source_format,
                target_format=target_format
            )
    
    def validate_format(self, 
                       content: Dict[str, str],
                       format_id: str) -> Dict[str, Any]:
        """
        验证格式
        
        Args:
            content: 内容
            format_id: 格式ID
            
        Returns:
            验证结果
        """
        try:
            journal_format = self.journal_formats.get(format_id)
            if not journal_format:
                return {
                    'is_valid': False,
                    'errors': [f"未找到格式定义: {format_id}"],
                    'warnings': []
                }
            
            validation_result = {
                'is_valid': True,
                'errors': [],
                'warnings': []
            }
            
            # 结构验证
            sections = list(content.keys())
            structure_valid, structure_errors = journal_format.validate_structure(sections)
            if not structure_valid:
                validation_result['is_valid'] = False
                validation_result['errors'].extend(structure_errors)
            
            # 内容验证
            for element_name, element_content in content.items():
                if element_content and element_content.strip():
                    element_enum = self._get_format_element_enum(element_name)
                    if element_enum:
                        format_rule = journal_format.get_format_rule(element_enum)
                        if format_rule:
                            content_valid, content_errors = format_rule.validate_content(element_content)
                            if not content_valid:
                                validation_result['errors'].extend([
                                    f"{element_name}: {error}" for error in content_errors
                                ])
                                validation_result['is_valid'] = False
            
            # 长度限制验证
            if journal_format.word_limit:
                total_words = sum(len(content.split()) for content in content.values() if content)
                min_words, max_words = journal_format.word_limit
                if total_words < min_words:
                    validation_result['warnings'].append(f"总字数不足: {total_words} < {min_words}")
                elif total_words > max_words:
                    validation_result['errors'].append(f"总字数超限: {total_words} > {max_words}")
                    validation_result['is_valid'] = False
            
            return validation_result
            
        except Exception as e:
            self.logger.error(f"格式验证失败: {str(e)}")
            return {
                'is_valid': False,
                'errors': [f"验证过程出错: {str(e)}"],
                'warnings': []
            }
    
    def get_format_requirements(self, format_id: str) -> Dict[str, Any]:
        """
        获取格式要求
        
        Args:
            format_id: 格式ID
            
        Returns:
            格式要求信息
        """
        journal_format = self.journal_formats.get(format_id)
        if not journal_format:
            return {}
        
        return {
            'journal_name': journal_format.journal_name,
            'publisher': journal_format.publisher,
            'citation_style': journal_format.citation_style.value,
            'word_limit': journal_format.word_limit,
            'page_limit': journal_format.page_limit,
            'required_sections': journal_format.required_sections,
            'optional_sections': journal_format.optional_sections,
            'section_order': journal_format.section_order,
            'special_requirements': journal_format.special_requirements,
            'format_rules': {
                element: {
                    'font_family': rule.font_family,
                    'font_size': rule.font_size,
                    'max_length': rule.max_length,
                    'min_length': rule.min_length,
                    'required_elements': rule.required_elements
                }
                for element, rule in journal_format.format_rules.items()
            }
        }
    
    def list_supported_formats(self) -> List[Dict[str, str]]:
        """列出支持的格式"""
        return [
            {
                'id': format_id,
                'name': journal_format.journal_name,
                'type': journal_format.journal_type.value,
                'publisher': journal_format.publisher,
                'description': journal_format.description
            }
            for format_id, journal_format in self.journal_formats.items()
        ]
    
    def suggest_format_improvements(self, 
                                  content: Dict[str, str],
                                  format_id: str) -> List[Dict[str, str]]:
        """
        建议格式改进
        
        Args:
            content: 内容
            format_id: 格式ID
            
        Returns:
            改进建议列表
        """
        suggestions = []
        
        try:
            journal_format = self.journal_formats.get(format_id)
            if not journal_format:
                return suggestions
            
            # 验证当前格式
            validation_result = self.validate_format(content, format_id)
            
            # 基于验证错误生成建议
            for error in validation_result['errors']:
                if "长度超过限制" in error:
                    suggestions.append({
                        'type': 'length',
                        'priority': 'high',
                        'description': '内容长度超过限制',
                        'suggestion': '请缩短内容或分解为多个部分'
                    })
                elif "缺少必需章节" in error:
                    suggestions.append({
                        'type': 'structure',
                        'priority': 'critical',
                        'description': error,
                        'suggestion': '请添加缺少的章节'
                    })
                elif "章节顺序错误" in error:
                    suggestions.append({
                        'type': 'structure',
                        'priority': 'medium',
                        'description': error,
                        'suggestion': '请调整章节顺序'
                    })
            
            # 基于警告生成建议
            for warning in validation_result['warnings']:
                if "字数不足" in warning:
                    suggestions.append({
                        'type': 'length',
                        'priority': 'low',
                        'description': warning,
                        'suggestion': '建议扩充内容以达到最低字数要求'
                    })
            
            # 格式特定建议
            if journal_format.journal_type == JournalType.IEEE:
                suggestions.extend(self._get_ieee_specific_suggestions(content))
            elif journal_format.journal_type == JournalType.NATURE:
                suggestions.extend(self._get_nature_specific_suggestions(content))
            
            return suggestions
            
        except Exception as e:
            self.logger.error(f"生成格式改进建议失败: {str(e)}")
            return suggestions
    
    # 格式初始化方法
    def _initialize_journal_formats(self):
        """初始化期刊格式"""
        # IEEE格式
        ieee_format = self._create_ieee_format()
        self.journal_formats[ieee_format.format_id] = ieee_format
        
        # ACM格式
        acm_format = self._create_acm_format()
        self.journal_formats[acm_format.format_id] = acm_format
        
        # Springer格式
        springer_format = self._create_springer_format()
        self.journal_formats[springer_format.format_id] = springer_format
        
        # Elsevier格式
        elsevier_format = self._create_elsevier_format()
        self.journal_formats[elsevier_format.format_id] = elsevier_format
        
        # Nature格式
        nature_format = self._create_nature_format()
        self.journal_formats[nature_format.format_id] = nature_format
        
        # 通用格式
        generic_format = self._create_generic_format()
        self.journal_formats[generic_format.format_id] = generic_format
    
    def _create_ieee_format(self) -> JournalFormat:
        """创建IEEE格式"""
        ieee_format = JournalFormat(
            format_id="ieee_standard",
            journal_name="IEEE Standard Format",
            journal_type=JournalType.IEEE,
            publisher="IEEE",
            description="IEEE期刊标准格式",
            citation_style=CitationStyle.IEEE_STYLE,
            word_limit=(3000, 8000),
            page_limit=(6, 12),
            required_sections=[
                "title", "abstract", "keywords", "introduction", 
                "methodology", "results", "conclusion", "references"
            ],
            optional_sections=["acknowledgments", "appendix"],
            section_order=[
                "title", "abstract", "keywords", "introduction",
                "methodology", "results", "discussion", "conclusion",
                "acknowledgments", "references", "appendix"
            ]
        )
        
        # 添加格式规则
        ieee_format.add_format_rule(
            FormatElement.TITLE,
            FormatRule(
                element=FormatElement.TITLE,
                font_size=14,
                font_weight="bold",
                alignment="center",
                max_length=100,
                capitalization="title"
            )
        )
        
        ieee_format.add_format_rule(
            FormatElement.ABSTRACT,
            FormatRule(
                element=FormatElement.ABSTRACT,
                font_size=10,
                font_style="italic",
                max_length=250,
                min_length=100,
                required_elements=["background", "method", "results", "conclusion"]
            )
        )
        
        ieee_format.add_format_rule(
            FormatElement.KEYWORDS,
            FormatRule(
                element=FormatElement.KEYWORDS,
                font_size=10,
                max_length=100,
                format_pattern="Index Terms—keyword1, keyword2, keyword3"
            )
        )
        
        return ieee_format
    
    def _create_acm_format(self) -> JournalFormat:
        """创建ACM格式"""
        acm_format = JournalFormat(
            format_id="acm_standard",
            journal_name="ACM Standard Format",
            journal_type=JournalType.ACM,
            publisher="ACM",
            description="ACM期刊标准格式",
            citation_style=CitationStyle.APA,
            word_limit=(4000, 10000),
            page_limit=(8, 15),
            required_sections=[
                "title", "abstract", "keywords", "introduction",
                "related_work", "methodology", "evaluation", "conclusion", "references"
            ],
            optional_sections=["acknowledgments", "appendix"]
        )
        
        # 添加ACM特定的格式规则
        acm_format.add_format_rule(
            FormatElement.TITLE,
            FormatRule(
                element=FormatElement.TITLE,
                font_size=18,
                font_weight="bold",
                alignment="left",
                max_length=120
            )
        )
        
        acm_format.add_format_rule(
            FormatElement.ABSTRACT,
            FormatRule(
                element=FormatElement.ABSTRACT,
                max_length=300,
                min_length=150,
                required_elements=["problem", "approach", "results"]
            )
        )
        
        return acm_format
    
    def _create_springer_format(self) -> JournalFormat:
        """创建Springer格式"""
        springer_format = JournalFormat(
            format_id="springer_standard",
            journal_name="Springer Standard Format",
            journal_type=JournalType.SPRINGER,
            publisher="Springer",
            description="Springer期刊标准格式",
            citation_style=CitationStyle.APA,
            word_limit=(5000, 12000),
            page_limit=(10, 20),
            required_sections=[
                "title", "abstract", "keywords", "introduction",
                "literature_review", "methodology", "results", 
                "discussion", "conclusion", "references"
            ]
        )
        
        # Springer特定规则
        springer_format.add_format_rule(
            FormatElement.ABSTRACT,
            FormatRule(
                element=FormatElement.ABSTRACT,
                max_length=350,
                min_length=200,
                required_elements=["purpose", "design", "findings", "implications"]
            )
        )
        
        return springer_format
    
    def _create_elsevier_format(self) -> JournalFormat:
        """创建Elsevier格式"""
        elsevier_format = JournalFormat(
            format_id="elsevier_standard",
            journal_name="Elsevier Standard Format",
            journal_type=JournalType.ELSEVIER,
            publisher="Elsevier",
            description="Elsevier期刊标准格式",
            citation_style=CitationStyle.HARVARD,
            word_limit=(4000, 10000),
            page_limit=(8, 16)
        )
        
        return elsevier_format
    
    def _create_nature_format(self) -> JournalFormat:
        """创建Nature格式"""
        nature_format = JournalFormat(
            format_id="nature_standard",
            journal_name="Nature Standard Format",
            journal_type=JournalType.NATURE,
            publisher="Nature Publishing Group",
            description="Nature期刊标准格式",
            citation_style=CitationStyle.NATURE_STYLE,
            word_limit=(2000, 5000),
            page_limit=(4, 8),
            required_sections=[
                "title", "abstract", "introduction", "results",
                "discussion", "methods", "references"
            ],
            special_requirements=[
                "摘要不超过200字",
                "引言和讨论合并",
                "方法部分放在最后"
            ]
        )
        
        # Nature特定规则
        nature_format.add_format_rule(
            FormatElement.ABSTRACT,
            FormatRule(
                element=FormatElement.ABSTRACT,
                max_length=200,
                min_length=100,
                required_elements=["significance", "results", "conclusions"]
            )
        )
        
        return nature_format
    
    def _create_generic_format(self) -> JournalFormat:
        """创建通用格式"""
        generic_format = JournalFormat(
            format_id="generic_standard",
            journal_name="Generic Academic Format",
            journal_type=JournalType.GENERIC,
            publisher="Generic",
            description="通用学术论文格式",
            citation_style=CitationStyle.APA,
            required_sections=[
                "title", "abstract", "introduction", "methodology",
                "results", "discussion", "conclusion", "references"
            ]
        )
        
        return generic_format
    
    # 转换方法
    def _convert_element(self, 
                        element_name: str,
                        content: str,
                        source_format: Optional[JournalFormat],
                        target_format: JournalFormat,
                        config: AdapterConfig) -> str:
        """转换单个元素"""
        # 获取转换器
        converter_name = self._get_converter_name(element_name)
        if converter_name in self.format_converters:
            converter = self.format_converters[converter_name]
            return converter(content, source_format, target_format, config)
        
        # 默认处理
        return self._apply_basic_formatting(content, element_name, target_format, config)
    
    def _get_converter_name(self, element_name: str) -> str:
        """获取转换器名称"""
        converter_mapping = {
            'title': 'title',
            'author': 'author', 
            'abstract': 'abstract',
            'introduction': 'section',
            'methodology': 'section',
            'results': 'section',
            'discussion': 'section',
            'conclusion': 'section',
            'references': 'reference',
            'figures': 'figure',
            'tables': 'table'
        }
        return converter_mapping.get(element_name, 'section')
    
    def _convert_citations(self, 
                          content: str,
                          source_format: Optional[JournalFormat],
                          target_format: JournalFormat,
                          config: AdapterConfig) -> str:
        """转换引用格式"""
        if not config.convert_citations:
            return content
        
        # 简化的引用转换逻辑
        target_style = target_format.citation_style
        
        if target_style == CitationStyle.IEEE_STYLE:
            # 转换为IEEE数字格式 [1], [2], [3]
            content = re.sub(r'\(([^)]+)\)', r'[\1]', content)
        elif target_style == CitationStyle.APA:
            # 转换为APA格式 (Author, Year)
            content = re.sub(r'\[(\d+)\]', r'(Ref\1)', content)
        elif target_style == CitationStyle.NATURE_STYLE:
            # Nature使用上标数字
            content = re.sub(r'\[(\d+)\]', r'<sup>\1</sup>', content)
        
        return content
    
    def _convert_references(self, 
                           content: str,
                           source_format: Optional[JournalFormat],
                           target_format: JournalFormat,
                           config: AdapterConfig) -> str:
        """转换参考文献格式"""
        # 这里实现参考文献格式转换逻辑
        # 简化实现，实际需要更复杂的解析和转换
        return content
    
    def _convert_title_format(self, 
                             content: str,
                             source_format: Optional[JournalFormat],
                             target_format: JournalFormat,
                             config: AdapterConfig) -> str:
        """转换标题格式"""
        title_rule = target_format.get_format_rule(FormatElement.TITLE)
        if title_rule:
            if title_rule.capitalization == "title":
                # 标题大小写
                content = content.title()
            elif title_rule.capitalization == "upper":
                content = content.upper()
            elif title_rule.capitalization == "lower":
                content = content.lower()
        
        return content
    
    def _convert_author_format(self, 
                              content: str,
                              source_format: Optional[JournalFormat],
                              target_format: JournalFormat,
                              config: AdapterConfig) -> str:
        """转换作者格式"""
        # 实现作者格式转换
        return content
    
    def _convert_abstract_format(self, 
                                content: str,
                                source_format: Optional[JournalFormat],
                                target_format: JournalFormat,
                                config: AdapterConfig) -> str:
        """转换摘要格式"""
        abstract_rule = target_format.get_format_rule(FormatElement.ABSTRACT)
        if abstract_rule and abstract_rule.max_length:
            if len(content) > abstract_rule.max_length:
                # 截断过长的摘要
                content = content[:abstract_rule.max_length - 3] + "..."
        
        return content
    
    def _convert_section_format(self, 
                               content: str,
                               source_format: Optional[JournalFormat],
                               target_format: JournalFormat,
                               config: AdapterConfig) -> str:
        """转换章节格式"""
        if config.normalize_whitespace:
            # 规范化空白字符
            content = re.sub(r'\s+', ' ', content.strip())
        
        return content
    
    def _convert_figure_format(self, 
                              content: str,
                              source_format: Optional[JournalFormat],
                              target_format: JournalFormat,
                              config: AdapterConfig) -> str:
        """转换图片格式"""
        # 实现图片格式转换
        return content
    
    def _convert_table_format(self, 
                             content: str,
                             source_format: Optional[JournalFormat],
                             target_format: JournalFormat,
                             config: AdapterConfig) -> str:
        """转换表格格式"""
        # 实现表格格式转换
        return content
    
    def _apply_basic_formatting(self, 
                               content: str,
                               element_name: str,
                               target_format: JournalFormat,
                               config: AdapterConfig) -> str:
        """应用基础格式化"""
        if config.normalize_whitespace:
            content = re.sub(r'\s+', ' ', content.strip())
        
        if config.fix_encoding:
            # 修复编码问题
            content = content.encode('utf-8', errors='ignore').decode('utf-8')
        
        return content  
  
    # 验证方法
    def _validate_structure(self, content: Dict[str, str], format_id: str) -> Tuple[bool, List[str]]:
        """验证结构"""
        journal_format = self.journal_formats.get(format_id)
        if not journal_format:
            return False, [f"未找到格式定义: {format_id}"]
        
        sections = list(content.keys())
        return journal_format.validate_structure(sections)
    
    def _validate_content(self, content: Dict[str, str], format_id: str) -> Tuple[bool, List[str]]:
        """验证内容"""
        journal_format = self.journal_formats.get(format_id)
        if not journal_format:
            return False, [f"未找到格式定义: {format_id}"]
        
        errors = []
        
        for element_name, element_content in content.items():
            if element_content and element_content.strip():
                element_enum = self._get_format_element_enum(element_name)
                if element_enum:
                    format_rule = journal_format.get_format_rule(element_enum)
                    if format_rule:
                        is_valid, content_errors = format_rule.validate_content(element_content)
                        if not is_valid:
                            errors.extend([f"{element_name}: {error}" for error in content_errors])
        
        return len(errors) == 0, errors
    
    def _validate_formatting(self, content: Dict[str, str], format_id: str) -> Tuple[bool, List[str]]:
        """验证格式化"""
        # 简化的格式化验证
        errors = []
        
        # 检查基本格式要求
        for element_name, element_content in content.items():
            if element_content:
                # 检查是否包含不当的格式标记
                if '<script>' in element_content.lower():
                    errors.append(f"{element_name}: 包含不安全的脚本标记")
                
                # 检查编码问题
                try:
                    element_content.encode('utf-8')
                except UnicodeEncodeError:
                    errors.append(f"{element_name}: 包含编码问题")
        
        return len(errors) == 0, errors
    
    def _validate_references(self, content: Dict[str, str], format_id: str) -> Tuple[bool, List[str]]:
        """验证参考文献"""
        errors = []
        
        references_content = content.get('references', '')
        if references_content:
            # 检查引用格式
            journal_format = self.journal_formats.get(format_id)
            if journal_format:
                citation_style = journal_format.citation_style
                
                if citation_style == CitationStyle.IEEE_STYLE:
                    # IEEE格式应该使用数字引用
                    if not re.search(r'\[\d+\]', references_content):
                        errors.append("IEEE格式应使用数字引用 [1], [2], ...")
                
                elif citation_style == CitationStyle.APA:
                    # APA格式应该包含年份
                    if not re.search(r'\(\d{4}\)', references_content):
                        errors.append("APA格式应包含年份信息")
        
        return len(errors) == 0, errors
    
    # 辅助方法
    def _get_format_element_enum(self, element_name: str) -> Optional[FormatElement]:
        """获取格式元素枚举"""
        element_mapping = {
            'title': FormatElement.TITLE,
            'author': FormatElement.AUTHOR,
            'affiliation': FormatElement.AFFILIATION,
            'abstract': FormatElement.ABSTRACT,
            'keywords': FormatElement.KEYWORDS,
            'introduction': FormatElement.INTRODUCTION,
            'methodology': FormatElement.METHODOLOGY,
            'results': FormatElement.RESULTS,
            'discussion': FormatElement.DISCUSSION,
            'conclusion': FormatElement.CONCLUSION,
            'references': FormatElement.REFERENCES,
            'figures': FormatElement.FIGURES,
            'tables': FormatElement.TABLES,
            'appendix': FormatElement.APPENDIX,
            'acknowledgments': FormatElement.ACKNOWLEDGMENTS
        }
        return element_mapping.get(element_name.lower())
    
    def _calculate_conversion_quality(self, result: FormatConversionResult) -> float:
        """计算转换质量"""
        quality_factors = []
        
        # 转换成功率
        if result.elements_converted > 0:
            success_rate = result.elements_converted / (result.elements_converted + len(result.warnings))
            quality_factors.append(success_rate)
        
        # 验证通过率
        if result.validation_passed:
            quality_factors.append(1.0)
        else:
            # 根据错误数量计算部分分数
            error_penalty = min(len(result.validation_errors) * 0.1, 0.8)
            quality_factors.append(1.0 - error_penalty)
        
        # 警告影响
        if len(result.warnings) == 0:
            quality_factors.append(1.0)
        else:
            warning_penalty = min(len(result.warnings) * 0.05, 0.3)
            quality_factors.append(1.0 - warning_penalty)
        
        return sum(quality_factors) / len(quality_factors) if quality_factors else 0.0
    
    def _calculate_format_compliance(self, content: Dict[str, str], journal_format: JournalFormat) -> float:
        """计算格式合规性"""
        compliance_score = 1.0
        
        # 检查必需章节
        sections = list(content.keys())
        missing_required = [s for s in journal_format.required_sections if s not in sections]
        if missing_required:
            compliance_score -= len(missing_required) * 0.2
        
        # 检查字数限制
        if journal_format.word_limit:
            total_words = sum(len(text.split()) for text in content.values() if text)
            min_words, max_words = journal_format.word_limit
            
            if total_words < min_words:
                compliance_score -= 0.1
            elif total_words > max_words:
                compliance_score -= 0.3
        
        # 检查格式规则合规性
        rule_violations = 0
        total_rules = 0
        
        for element_name, element_content in content.items():
            if element_content:
                element_enum = self._get_format_element_enum(element_name)
                if element_enum:
                    format_rule = journal_format.get_format_rule(element_enum)
                    if format_rule:
                        total_rules += 1
                        is_valid, _ = format_rule.validate_content(element_content)
                        if not is_valid:
                            rule_violations += 1
        
        if total_rules > 0:
            rule_compliance = 1.0 - (rule_violations / total_rules)
            compliance_score *= rule_compliance
        
        return max(0.0, compliance_score)
    
    def _get_ieee_specific_suggestions(self, content: Dict[str, str]) -> List[Dict[str, str]]:
        """获取IEEE特定建议"""
        suggestions = []
        
        # 检查摘要格式
        abstract = content.get('abstract', '')
        if abstract and not abstract.startswith('Abstract—'):
            suggestions.append({
                'type': 'format',
                'priority': 'medium',
                'description': 'IEEE摘要应以"Abstract—"开头',
                'suggestion': '请在摘要开头添加"Abstract—"'
            })
        
        # 检查关键词格式
        keywords = content.get('keywords', '')
        if keywords and not keywords.startswith('Index Terms—'):
            suggestions.append({
                'type': 'format',
                'priority': 'medium',
                'description': 'IEEE关键词应以"Index Terms—"开头',
                'suggestion': '请在关键词开头添加"Index Terms—"'
            })
        
        return suggestions
    
    def _get_nature_specific_suggestions(self, content: Dict[str, str]) -> List[Dict[str, str]]:
        """获取Nature特定建议"""
        suggestions = []
        
        # 检查摘要长度
        abstract = content.get('abstract', '')
        if abstract and len(abstract.split()) > 200:
            suggestions.append({
                'type': 'length',
                'priority': 'high',
                'description': 'Nature摘要不应超过200字',
                'suggestion': '请将摘要缩短至200字以内'
            })
        
        # 检查是否有单独的讨论章节
        if 'discussion' in content and 'conclusion' in content:
            suggestions.append({
                'type': 'structure',
                'priority': 'medium',
                'description': 'Nature通常将讨论和结论合并',
                'suggestion': '考虑将讨论和结论合并为一个章节'
            })
        
        return suggestions
    
    def auto_fix_common_issues(self, 
                              content: Dict[str, str],
                              format_id: str) -> Dict[str, str]:
        """自动修复常见问题"""
        fixed_content = content.copy()
        journal_format = self.journal_formats.get(format_id)
        
        if not journal_format:
            return fixed_content
        
        # 修复标题格式
        if 'title' in fixed_content:
            title_rule = journal_format.get_format_rule(FormatElement.TITLE)
            if title_rule:
                title = fixed_content['title']
                
                # 应用大小写规则
                if title_rule.capitalization == "title":
                    fixed_content['title'] = title.title()
                elif title_rule.capitalization == "upper":
                    fixed_content['title'] = title.upper()
                elif title_rule.capitalization == "lower":
                    fixed_content['title'] = title.lower()
                
                # 截断过长标题
                if title_rule.max_length and len(title) > title_rule.max_length:
                    fixed_content['title'] = title[:title_rule.max_length - 3] + "..."
        
        # 修复摘要格式
        if 'abstract' in fixed_content:
            abstract_rule = journal_format.get_format_rule(FormatElement.ABSTRACT)
            if abstract_rule and abstract_rule.max_length:
                abstract = fixed_content['abstract']
                if len(abstract) > abstract_rule.max_length:
                    fixed_content['abstract'] = abstract[:abstract_rule.max_length - 3] + "..."
        
        # 修复IEEE特定格式
        if journal_format.journal_type == JournalType.IEEE:
            if 'abstract' in fixed_content and not fixed_content['abstract'].startswith('Abstract—'):
                fixed_content['abstract'] = 'Abstract—' + fixed_content['abstract']
            
            if 'keywords' in fixed_content and not fixed_content['keywords'].startswith('Index Terms—'):
                fixed_content['keywords'] = 'Index Terms—' + fixed_content['keywords']
        
        # 规范化空白字符
        for key, value in fixed_content.items():
            if isinstance(value, str):
                fixed_content[key] = re.sub(r'\s+', ' ', value.strip())
        
        return fixed_content
    
    def generate_format_report(self, 
                              content: Dict[str, str],
                              format_id: str) -> Dict[str, Any]:
        """生成格式报告"""
        journal_format = self.journal_formats.get(format_id)
        if not journal_format:
            return {'error': f'未找到格式定义: {format_id}'}
        
        # 验证格式
        validation_result = self.validate_format(content, format_id)
        
        # 计算统计信息
        total_words = sum(len(text.split()) for text in content.values() if text)
        total_sections = len([k for k, v in content.items() if v and v.strip()])
        
        # 生成建议
        suggestions = self.suggest_format_improvements(content, format_id)
        
        report = {
            'format_info': {
                'format_id': format_id,
                'journal_name': journal_format.journal_name,
                'publisher': journal_format.publisher,
                'citation_style': journal_format.citation_style.value
            },
            'validation': validation_result,
            'statistics': {
                'total_words': total_words,
                'total_sections': total_sections,
                'word_limit': journal_format.word_limit,
                'page_limit': journal_format.page_limit
            },
            'compliance': {
                'required_sections_present': [
                    s for s in journal_format.required_sections 
                    if s in content and content[s].strip()
                ],
                'missing_required_sections': [
                    s for s in journal_format.required_sections 
                    if s not in content or not content[s].strip()
                ],
                'optional_sections_present': [
                    s for s in journal_format.optional_sections 
                    if s in content and content[s].strip()
                ]
            },
            'suggestions': suggestions,
            'generated_time': datetime.datetime.now().isoformat()
        }
        
        return report
    
    def batch_convert_formats(self, 
                             contents: List[Dict[str, str]],
                             source_format: str,
                             target_formats: List[str],
                             config: AdapterConfig = None) -> Dict[str, List[FormatConversionResult]]:
        """批量格式转换"""
        if config is None:
            config = AdapterConfig()
        
        results = {}
        
        for target_format in target_formats:
            results[target_format] = []
            
            for i, content in enumerate(contents):
                try:
                    result = self.convert_format(content, source_format, target_format, config)
                    results[target_format].append(result)
                    
                    self.logger.info(f"批量转换进度: {target_format} {i+1}/{len(contents)}")
                    
                except Exception as e:
                    error_result = FormatConversionResult(
                        success=False,
                        error_message=str(e),
                        source_format=source_format,
                        target_format=target_format
                    )
                    results[target_format].append(error_result)
        
        return results
    
    def export_format_definition(self, format_id: str) -> Optional[Dict[str, Any]]:
        """导出格式定义"""
        journal_format = self.journal_formats.get(format_id)
        if not journal_format:
            return None
        
        return {
            'format_id': journal_format.format_id,
            'journal_name': journal_format.journal_name,
            'journal_type': journal_format.journal_type.value,
            'publisher': journal_format.publisher,
            'description': journal_format.description,
            'version': journal_format.version,
            'page_settings': {
                'page_size': journal_format.page_size,
                'page_margins': journal_format.page_margins
            },
            'font_settings': {
                'default_font_family': journal_format.default_font_family,
                'default_font_size': journal_format.default_font_size,
                'default_line_spacing': journal_format.default_line_spacing
            },
            'citation_style': journal_format.citation_style.value,
            'structure': {
                'required_sections': journal_format.required_sections,
                'optional_sections': journal_format.optional_sections,
                'section_order': journal_format.section_order
            },
            'limits': {
                'word_limit': journal_format.word_limit,
                'page_limit': journal_format.page_limit,
                'reference_limit': journal_format.reference_limit,
                'figure_limit': journal_format.figure_limit,
                'table_limit': journal_format.table_limit
            },
            'format_rules': {
                element: {
                    'font_family': rule.font_family,
                    'font_size': rule.font_size,
                    'font_weight': rule.font_weight,
                    'font_style': rule.font_style,
                    'alignment': rule.alignment,
                    'max_length': rule.max_length,
                    'min_length': rule.min_length,
                    'required_elements': rule.required_elements,
                    'format_pattern': rule.format_pattern
                }
                for element, rule in journal_format.format_rules.items()
            },
            'special_requirements': journal_format.special_requirements,
            'last_updated': journal_format.last_updated.isoformat()
        }
    
    def import_format_definition(self, format_data: Dict[str, Any]) -> bool:
        """导入格式定义"""
        try:
            journal_format = JournalFormat(
                format_id=format_data['format_id'],
                journal_name=format_data['journal_name'],
                journal_type=JournalType(format_data['journal_type']),
                publisher=format_data['publisher'],
                description=format_data.get('description', ''),
                version=format_data.get('version', '1.0')
            )
            
            # 设置页面和字体
            if 'page_settings' in format_data:
                page_settings = format_data['page_settings']
                journal_format.page_size = page_settings.get('page_size', 'A4')
                journal_format.page_margins = page_settings.get('page_margins', {})
            
            if 'font_settings' in format_data:
                font_settings = format_data['font_settings']
                journal_format.default_font_family = font_settings.get('default_font_family', 'Times New Roman')
                journal_format.default_font_size = font_settings.get('default_font_size', 12)
                journal_format.default_line_spacing = font_settings.get('default_line_spacing', 1.5)
            
            # 设置引用格式
            if 'citation_style' in format_data:
                journal_format.citation_style = CitationStyle(format_data['citation_style'])
            
            # 设置结构
            if 'structure' in format_data:
                structure = format_data['structure']
                journal_format.required_sections = structure.get('required_sections', [])
                journal_format.optional_sections = structure.get('optional_sections', [])
                journal_format.section_order = structure.get('section_order', [])
            
            # 设置限制
            if 'limits' in format_data:
                limits = format_data['limits']
                journal_format.word_limit = limits.get('word_limit')
                journal_format.page_limit = limits.get('page_limit')
                journal_format.reference_limit = limits.get('reference_limit')
                journal_format.figure_limit = limits.get('figure_limit')
                journal_format.table_limit = limits.get('table_limit')
            
            # 设置格式规则
            if 'format_rules' in format_data:
                for element_name, rule_data in format_data['format_rules'].items():
                    element_enum = self._get_format_element_enum(element_name)
                    if element_enum:
                        format_rule = FormatRule(
                            element=element_enum,
                            font_family=rule_data.get('font_family'),
                            font_size=rule_data.get('font_size'),
                            font_weight=rule_data.get('font_weight'),
                            font_style=rule_data.get('font_style'),
                            alignment=rule_data.get('alignment'),
                            max_length=rule_data.get('max_length'),
                            min_length=rule_data.get('min_length'),
                            required_elements=rule_data.get('required_elements', []),
                            format_pattern=rule_data.get('format_pattern')
                        )
                        journal_format.add_format_rule(element_enum, format_rule)
            
            # 设置特殊要求
            journal_format.special_requirements = format_data.get('special_requirements', [])
            
            # 添加到格式库
            self.journal_formats[journal_format.format_id] = journal_format
            
            self.logger.info(f"成功导入格式定义: {journal_format.format_id}")
            return True
            
        except Exception as e:
            self.logger.error(f"导入格式定义失败: {str(e)}")
            return False 
   
    # 验证方法
    def _validate_structure(self, content: Dict[str, str], format_id: str) -> Tuple[bool, List[str]]:
        """验证结构"""
        journal_format = self.journal_f   
 
    # 验证方法
    def _validate_structure(self, content: Dict[str, str], format_id: str) -> Tuple[bool, List[str]]:
        """验证结构"""
        journal_format = self.journal_formats.get(format_id)
        if not journal_format:
            return False, [f"未找到格式定义: {format_id}"]
        
        return journal_format.validate_structure(list(content.keys()))
    
    def _validate_content(self, content: Dict[str, str], format_id: str) -> Tuple[bool, List[str]]:
        """验证内容"""
        journal_format = self.journal_formats.get(format_id)
        if not journal_format:
            return False, [f"未找到格式定义: {format_id}"]
        
        errors = []
        for element_name, element_content in content.items():
            if element_content and element_content.strip():
                element_enum = self._get_format_element_enum(element_name)
                if element_enum:
                    format_rule = journal_format.get_format_rule(element_enum)
                    if format_rule:
                        is_valid, content_errors = format_rule.validate_content(element_content)
                        if not is_valid:
                            errors.extend([f"{element_name}: {error}" for error in content_errors])
        
        return len(errors) == 0, errors
    
    def _validate_formatting(self, content: Dict[str, str], format_id: str) -> Tuple[bool, List[str]]:
        """验证格式化"""
        # 实现格式化验证逻辑
        errors = []
        
        # 检查字体、间距等格式要求
        journal_format = self.journal_formats.get(format_id)
        if journal_format:
            for element_name, element_content in content.items():
                element_enum = self._get_format_element_enum(element_name)
                if element_enum:
                    format_rule = journal_format.get_format_rule(element_enum)
                    if format_rule:
                        # 检查格式模式
                        if format_rule.format_pattern and element_content:
                            if not self._matches_pattern(element_content, format_rule.format_pattern):
                                errors.append(f"{element_name}: 格式不符合要求")
        
        return len(errors) == 0, errors
    
    def _validate_references(self, content: Dict[str, str], format_id: str) -> Tuple[bool, List[str]]:
        """验证参考文献"""
        errors = []
        
        if 'references' in content:
            references = content['references']
            journal_format = self.journal_formats.get(format_id)
            
            if journal_format and journal_format.reference_limit:
                # 简单计算参考文献数量
                ref_count = len(re.findall(r'\n\s*\d+\.|\n\s*\[\d+\]', references))
                if ref_count > journal_format.reference_limit:
                    errors.append(f"参考文献数量超限: {ref_count} > {journal_format.reference_limit}")
            
            # 检查引用格式
            citation_style = journal_format.citation_style if journal_format else CitationStyle.APA
            if not self._validate_citation_style(references, citation_style):
                errors.append("参考文献格式不符合要求")
        
        return len(errors) == 0, errors
    
    # 辅助方法
    def _get_format_element_enum(self, element_name: str) -> Optional[FormatElement]:
        """获取格式元素枚举"""
        element_mapping = {
            'title': FormatElement.TITLE,
            'author': FormatElement.AUTHOR,
            'affiliation': FormatElement.AFFILIATION,
            'abstract': FormatElement.ABSTRACT,
            'keywords': FormatElement.KEYWORDS,
            'introduction': FormatElement.INTRODUCTION,
            'methodology': FormatElement.METHODOLOGY,
            'results': FormatElement.RESULTS,
            'discussion': FormatElement.DISCUSSION,
            'conclusion': FormatElement.CONCLUSION,
            'references': FormatElement.REFERENCES,
            'figures': FormatElement.FIGURES,
            'tables': FormatElement.TABLES,
            'appendix': FormatElement.APPENDIX,
            'acknowledgments': FormatElement.ACKNOWLEDGMENTS
        }
        return element_mapping.get(element_name.lower())
    
    def _matches_pattern(self, content: str, pattern: str) -> bool:
        """检查内容是否匹配模式"""
        try:
            # 简化的模式匹配
            if "keyword1, keyword2" in pattern:
                # 关键词模式
                return ',' in content and len(content.split(',')) >= 2
            return True
        except:
            return True
    
    def _validate_citation_style(self, references: str, style: CitationStyle) -> bool:
        """验证引用格式"""
        if style == CitationStyle.IEEE_STYLE:
            # IEEE格式检查：[1] Author, "Title," Journal, vol. X, no. Y, pp. Z-W, Year.
            pattern = r'\[\d+\]\s+[A-Z].*?["\'].*?["\'].*?\d{4}'
            return bool(re.search(pattern, references))
        elif style == CitationStyle.APA:
            # APA格式检查：Author, A. A. (Year). Title. Journal, Volume(Issue), pages.
            pattern = r'[A-Z][a-z]+.*?\(\d{4}\).*?\.'
            return bool(re.search(pattern, references))
        elif style == CitationStyle.NATURE_STYLE:
            # Nature格式检查：Author, A. Title. Journal vol, pages (year).
            pattern = r'[A-Z][a-z]+.*?\d+,.*?\(\d{4}\)'
            return bool(re.search(pattern, references))
        
        return True  # 默认通过
    
    def _calculate_conversion_quality(self, result: FormatConversionResult) -> float:
        """计算转换质量"""
        quality_factors = []
        
        # 转换成功率
        if result.elements_converted > 0:
            success_rate = result.elements_converted / (result.elements_converted + len(result.warnings))
            quality_factors.append(success_rate)
        
        # 验证通过率
        if result.validation_passed:
            quality_factors.append(1.0)
        else:
            # 根据错误数量计算
            error_penalty = min(len(result.validation_errors) * 0.1, 0.5)
            quality_factors.append(1.0 - error_penalty)
        
        # 警告影响
        if len(result.warnings) == 0:
            quality_factors.append(1.0)
        else:
            warning_penalty = min(len(result.warnings) * 0.05, 0.3)
            quality_factors.append(1.0 - warning_penalty)
        
        return sum(quality_factors) / len(quality_factors) if quality_factors else 0.0
    
    def _calculate_format_compliance(self, content: Dict[str, str], journal_format: JournalFormat) -> float:
        """计算格式合规性"""
        compliance_score = 1.0
        total_checks = 0
        passed_checks = 0
        
        # 检查必需章节
        for required_section in journal_format.required_sections:
            total_checks += 1
            if required_section in content and content[required_section].strip():
                passed_checks += 1
        
        # 检查字数限制
        if journal_format.word_limit:
            total_checks += 1
            total_words = sum(len(text.split()) for text in content.values() if text)
            min_words, max_words = journal_format.word_limit
            if min_words <= total_words <= max_words:
                passed_checks += 1
        
        # 检查格式规则
        for element_name, element_content in content.items():
            if element_content and element_content.strip():
                element_enum = self._get_format_element_enum(element_name)
                if element_enum:
                    format_rule = journal_format.get_format_rule(element_enum)
                    if format_rule:
                        total_checks += 1
                        is_valid, _ = format_rule.validate_content(element_content)
                        if is_valid:
                            passed_checks += 1
        
        return passed_checks / total_checks if total_checks > 0 else 1.0
    
    def _get_ieee_specific_suggestions(self, content: Dict[str, str]) -> List[Dict[str, str]]:
        """获取IEEE特定建议"""
        suggestions = []
        
        # IEEE特定检查
        if 'abstract' in content:
            abstract = content['abstract']
            if len(abstract.split()) > 250:
                suggestions.append({
                    'type': 'ieee_specific',
                    'priority': 'high',
                    'description': 'IEEE摘要字数超过250字限制',
                    'suggestion': '请将摘要缩短至250字以内'
                })
        
        if 'keywords' in content:
            keywords = content['keywords']
            if not keywords.startswith('Index Terms'):
                suggestions.append({
                    'type': 'ieee_specific',
                    'priority': 'medium',
                    'description': 'IEEE关键词格式不正确',
                    'suggestion': '关键词应以"Index Terms—"开头'
                })
        
        return suggestions
    
    def _get_nature_specific_suggestions(self, content: Dict[str, str]) -> List[Dict[str, str]]:
        """获取Nature特定建议"""
        suggestions = []
        
        # Nature特定检查
        if 'abstract' in content:
            abstract = content['abstract']
            if len(abstract.split()) > 200:
                suggestions.append({
                    'type': 'nature_specific',
                    'priority': 'critical',
                    'description': 'Nature摘要字数超过200字限制',
                    'suggestion': '请将摘要缩短至200字以内'
                })
        
        # 检查是否有单独的引言和讨论
        if 'introduction' in content and 'discussion' in content:
            suggestions.append({
                'type': 'nature_specific',
                'priority': 'medium',
                'description': 'Nature期刊通常将引言和讨论合并',
                'suggestion': '考虑将引言和讨论合并为一个章节'
            })
        
        return suggestions
    
    def create_custom_format(self, 
                           format_config: Dict[str, Any]) -> str:
        """
        创建自定义格式
        
        Args:
            format_config: 格式配置
            
        Returns:
            格式ID
        """
        try:
            format_id = format_config.get('format_id', f"custom_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}")
            
            custom_format = JournalFormat(
                format_id=format_id,
                journal_name=format_config.get('journal_name', 'Custom Journal'),
                journal_type=JournalType.GENERIC,
                publisher=format_config.get('publisher', 'Custom Publisher'),
                description=format_config.get('description', '自定义期刊格式'),
                citation_style=CitationStyle(format_config.get('citation_style', 'apa')),
                word_limit=format_config.get('word_limit'),
                page_limit=format_config.get('page_limit'),
                required_sections=format_config.get('required_sections', []),
                optional_sections=format_config.get('optional_sections', []),
                special_requirements=format_config.get('special_requirements', [])
            )
            
            # 添加格式规则
            if 'format_rules' in format_config:
                for element_name, rule_config in format_config['format_rules'].items():
                    element_enum = self._get_format_element_enum(element_name)
                    if element_enum:
                        format_rule = FormatRule(
                            element=element_enum,
                            font_family=rule_config.get('font_family'),
                            font_size=rule_config.get('font_size'),
                            font_weight=rule_config.get('font_weight'),
                            max_length=rule_config.get('max_length'),
                            min_length=rule_config.get('min_length'),
                            required_elements=rule_config.get('required_elements', []),
                            alignment=rule_config.get('alignment')
                        )
                        custom_format.add_format_rule(element_enum, format_rule)
            
            # 保存自定义格式
            self.journal_formats[format_id] = custom_format
            
            self.logger.info(f"创建自定义格式: {format_id}")
            return format_id
            
        except Exception as e:
            self.logger.error(f"创建自定义格式失败: {str(e)}")
            raise
    
    def export_format_definition(self, format_id: str) -> Dict[str, Any]:
        """
        导出格式定义
        
        Args:
            format_id: 格式ID
            
        Returns:
            格式定义字典
        """
        journal_format = self.journal_formats.get(format_id)
        if not journal_format:
            return {}
        
        return {
            'format_id': journal_format.format_id,
            'journal_name': journal_format.journal_name,
            'journal_type': journal_format.journal_type.value,
            'publisher': journal_format.publisher,
            'description': journal_format.description,
            'version': journal_format.version,
            'page_size': journal_format.page_size,
            'page_margins': journal_format.page_margins,
            'default_font_family': journal_format.default_font_family,
            'default_font_size': journal_format.default_font_size,
            'default_line_spacing': journal_format.default_line_spacing,
            'citation_style': journal_format.citation_style.value,
            'word_limit': journal_format.word_limit,
            'page_limit': journal_format.page_limit,
            'reference_limit': journal_format.reference_limit,
            'required_sections': journal_format.required_sections,
            'optional_sections': journal_format.optional_sections,
            'section_order': journal_format.section_order,
            'special_requirements': journal_format.special_requirements,
            'format_rules': {
                element: {
                    'font_family': rule.font_family,
                    'font_size': rule.font_size,
                    'font_weight': rule.font_weight,
                    'font_style': rule.font_style,
                    'alignment': rule.alignment,
                    'max_length': rule.max_length,
                    'min_length': rule.min_length,
                    'required_elements': rule.required_elements,
                    'format_pattern': rule.format_pattern
                }
                for element, rule in journal_format.format_rules.items()
            }
        }
    
    def import_format_definition(self, format_definition: Dict[str, Any]) -> str:
        """
        导入格式定义
        
        Args:
            format_definition: 格式定义字典
            
        Returns:
            格式ID
        """
        try:
            format_id = format_definition['format_id']
            
            journal_format = JournalFormat(
                format_id=format_id,
                journal_name=format_definition['journal_name'],
                journal_type=JournalType(format_definition['journal_type']),
                publisher=format_definition['publisher'],
                description=format_definition['description'],
                version=format_definition.get('version', '1.0'),
                page_size=format_definition.get('page_size', 'A4'),
                page_margins=format_definition.get('page_margins', {}),
                default_font_family=format_definition.get('default_font_family', 'Times New Roman'),
                default_font_size=format_definition.get('default_font_size', 12),
                default_line_spacing=format_definition.get('default_line_spacing', 1.5),
                citation_style=CitationStyle(format_definition.get('citation_style', 'apa')),
                word_limit=format_definition.get('word_limit'),
                page_limit=format_definition.get('page_limit'),
                reference_limit=format_definition.get('reference_limit'),
                required_sections=format_definition.get('required_sections', []),
                optional_sections=format_definition.get('optional_sections', []),
                section_order=format_definition.get('section_order', []),
                special_requirements=format_definition.get('special_requirements', [])
            )
            
            # 导入格式规则
            if 'format_rules' in format_definition:
                for element_name, rule_config in format_definition['format_rules'].items():
                    element_enum = self._get_format_element_enum(element_name)
                    if element_enum:
                        format_rule = FormatRule(
                            element=element_enum,
                            font_family=rule_config.get('font_family'),
                            font_size=rule_config.get('font_size'),
                            font_weight=rule_config.get('font_weight'),
                            font_style=rule_config.get('font_style'),
                            alignment=rule_config.get('alignment'),
                            max_length=rule_config.get('max_length'),
                            min_length=rule_config.get('min_length'),
                            required_elements=rule_config.get('required_elements', []),
                            format_pattern=rule_config.get('format_pattern')
                        )
                        journal_format.add_format_rule(element_enum, format_rule)
            
            # 保存导入的格式
            self.journal_formats[format_id] = journal_format
            
            self.logger.info(f"导入格式定义: {format_id}")
            return format_id
            
        except Exception as e:
            self.logger.error(f"导入格式定义失败: {str(e)}")
            raise
    
    def batch_convert_formats(self, 
                            contents: List[Dict[str, str]],
                            source_format: str,
                            target_formats: List[str],
                            config: AdapterConfig = None) -> Dict[str, List[FormatConversionResult]]:
        """
        批量格式转换
        
        Args:
            contents: 内容列表
            source_format: 源格式
            target_formats: 目标格式列表
            config: 配置
            
        Returns:
            转换结果字典
        """
        results = {}
        
        for target_format in target_formats:
            results[target_format] = []
            
            for content in contents:
                try:
                    result = self.convert_format(content, source_format, target_format, config)
                    results[target_format].append(result)
                except Exception as e:
                    error_result = FormatConversionResult(
                        success=False,
                        error_message=str(e),
                        source_format=source_format,
                        target_format=target_format
                    )
                    results[target_format].append(error_result)
        
        return results
    
    def get_format_compatibility_matrix(self) -> Dict[str, Dict[str, float]]:
        """
        获取格式兼容性矩阵
        
        Returns:
            兼容性矩阵（0-1之间的兼容性评分）
        """
        formats = list(self.journal_formats.keys())
        compatibility_matrix = {}
        
        for source_format in formats:
            compatibility_matrix[source_format] = {}
            source_journal = self.journal_formats[source_format]
            
            for target_format in formats:
                if source_format == target_format:
                    compatibility_matrix[source_format][target_format] = 1.0
                else:
                    target_journal = self.journal_formats[target_format]
                    compatibility_score = self._calculate_format_compatibility(source_journal, target_journal)
                    compatibility_matrix[source_format][target_format] = compatibility_score
        
        return compatibility_matrix
    
    def _calculate_format_compatibility(self, source: JournalFormat, target: JournalFormat) -> float:
        """计算格式兼容性"""
        compatibility_factors = []
        
        # 引用格式兼容性
        if source.citation_style == target.citation_style:
            compatibility_factors.append(1.0)
        else:
            compatibility_factors.append(0.7)  # 可以转换但需要处理
        
        # 结构兼容性
        source_sections = set(source.required_sections + source.optional_sections)
        target_sections = set(target.required_sections + target.optional_sections)
        
        if source_sections and target_sections:
            common_sections = source_sections.intersection(target_sections)
            structure_compatibility = len(common_sections) / len(source_sections.union(target_sections))
            compatibility_factors.append(structure_compatibility)
        
        # 长度限制兼容性
        if source.word_limit and target.word_limit:
            source_min, source_max = source.word_limit
            target_min, target_max = target.word_limit
            
            # 检查范围重叠
            overlap_min = max(source_min, target_min)
            overlap_max = min(source_max, target_max)
            
            if overlap_min <= overlap_max:
                overlap_ratio = (overlap_max - overlap_min) / (max(source_max, target_max) - min(source_min, target_min))
                compatibility_factors.append(overlap_ratio)
            else:
                compatibility_factors.append(0.3)  # 无重叠但可能可以调整
        
        return sum(compatibility_factors) / len(compatibility_factors) if compatibility_factors else 0.5